package xyz.larkin.common;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Created by liujin on 2018/8/6.
 *
 * @description TODO
 */

public class RedisConfig {

    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    private static Pattern hostPattern = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

    @Value("${spring.redis.cluster.nodes}")
    private String hostAndPorts;
    @Value("${spring.redis.maxDirections}")
    private Integer maxRedirections;
    @Value("${spring.redis.commandTimeout}")
    private Integer timeout;
    @Value("${spring.redis.jedis.pool.max-active}")
    private Integer maxTotal;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private Integer maxWaitMillis;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private Integer maxIdle;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private Integer minIdle;

    @Bean(name = "jedisCluster")//数据源配置
    public JedisCluster jedisCluster(@Qualifier("jedisPoolConfig") GenericObjectPoolConfig genericObjectPoolConfig ) {
        //创建jedisNode 初始化jedisCluster
        if(StringUtils.isEmpty(hostAndPorts)) {
            logger.error("redis host is empty!");
            throw new IllegalArgumentException("redis host is empty");
        }
        Set<HostAndPort> haps = parseHostAndPort(hostAndPorts);
        if(haps==null || haps.size()<= 0) {
            logger.error("no redis host is enable!");
            throw new IllegalArgumentException("no redis host is enable");
        }
        return  new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);
    }
/*
    @Bean(name = "dmSqlSessionFactory")//SqlSessionFactory配置
    @Primary
    public SqlSessionFactory dmSqlSessionFactory(@Qualifier("dmDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:sqlMapConfig.xml"));//po对象别名的xml文件
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));//mapper的xml文件
        return bean.getObject();
    }*/

    private Set<HostAndPort> parseHostAndPort(String hostAndPorts) {
        Set<HostAndPort> hapsSet = new HashSet<>();
        String[] hosts = hostAndPorts.split(",");
        for(String host : hosts) {
            if(!hostPattern.matcher(host).matches()) {
                return null;
            }
            String[] hostPort = host.split(":");
            if(hostPort.length !=2) {
                return null;
            }
            HostAndPort hostAndPort = new HostAndPort(hostPort[0], Integer.valueOf(hostPort[1]));
            hapsSet.add(hostAndPort);
        }
        return hapsSet;
    }

    @Bean(name = "jedisPoolConfig")
    public JedisPoolConfig getPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        return jedisPoolConfig;
    }
}
